package com.shycloud.mido.member.service.impl;

import com.joy.zebra.common.push.JPushUtils;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.homework.api.entity.WeekMain;
import com.shycloud.mido.homework.api.enums.JPushCodeEnum;
import com.shycloud.mido.member.api.entity.MsgMain;
import com.shycloud.mido.member.service.MsgMainService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.member.api.entity.MsgMemberInfo;
import com.shycloud.mido.member.mapper.MsgMemberInfoMapper;
import com.shycloud.mido.member.service.MsgMemberInfoService;

/**
 * 消息推送业务
 *
 * @author nianhua.jiang
 */
@Service
@AllArgsConstructor
public class MsgMemberInfoServiceImpl extends ServiceImpl<MsgMemberInfoMapper, MsgMemberInfo> implements MsgMemberInfoService {

	/** 发送消息模块 mapper */
	private MsgMemberInfoMapper memberInfoMapper;

	/** 消息主表业务 service */
	private MsgMainService msgMainService;

	@Override
	public boolean sendMsg(String msgId, String fromId, String toId) {
		MsgMemberInfo msgMemberInfo = new MsgMemberInfo();
		//消息ID
		msgMemberInfo.setMsgId(msgId);
		//接收方ID
		msgMemberInfo.setToId(toId);
		//发送方ID
		msgMemberInfo.setFromId(fromId);
		//创建时间
		msgMemberInfo.setCreateTime(LocalDateTime.now());
		msgMemberInfo.setDelFlag(CommonConstants.STATUS_NORMAL);
		return memberInfoMapper.insert(msgMemberInfo) == 1;
	}

	@Override
	public boolean sendWeekMsg(WeekMain weekMain) {

		//添加消息体
		MsgMain msgMain = new MsgMain();
		//标题
		msgMain.setTitle("周报");
		//信息
		msgMain.setMessage("收到上周练琴周报，请查阅");
		//不可修改
		msgMain.setModify("1");
		//周报
		msgMain.setMsgType("1");
		//发布时间
		msgMain.setPubDatetime(LocalDateTime.now());
		//实际发送时间
		msgMain.setActualPubDatetime(LocalDateTime.now());
		//全体发送
		msgMain.setRangeType("0");
		//范围内容:当为周报时记录周报的 weekId
		msgMain.setRangeText(weekMain.getId());
		//自动
		msgMain.setMode("1");
		//个人
		msgMain.setRangeType("1");
		//来自系统
		msgMain.setTriggerFrom("0");
		//发送目标(所有符合条件的用户)
		msgMain.setTriggerTo("0");
		//周报
		msgMain.setPoint("8");
		//创建时间
		msgMain.setCreateTime(LocalDateTime.now());

		String msgId = msgMainService.addSysMsg(msgMain);

		List<String> memberIds = memberInfoMapper.getWeekPushMemberIds(weekMain.getId());

		// 发送推送
		for (String memberId : memberIds) {
			sendMsg(msgId, "sys", memberId);
		}

		//获取待推送的人员的 memberId
		List<String> regIds = memberInfoMapper.getWeekPushRegIds(weekMain.getId());

		JPushUtils.sendJPush("周报", "收到上周练琴周报，请查阅", regIds);

		JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_APP_HOMEPAGE_VIEW.getType(), regIds, "通知APP请求getMsgApp接口");

		return true;
	}
}
